package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Http请求实践代码
 * */
public class HttpTestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_test);

        OkHttpClient client = new OkHttpClient();   // 1、初始化client对象
        Request request = new Request.Builder().url("http://10.182.61.11:7001/v1/test/getMembers").build();  // 2、配置请求的url
        // 3、发起异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 请求失败回调函数
                Log.i("tag1", e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                // 请求成功回调函数
                //Log.i("tag1", response.body().string());  // response.body().string()就是请求返回的数据

                String data = response.body().string();   // response.body().string()就是请求返回的数据
                // 把字符串转成对象
                Gson gson = new Gson();
                ArrayList<MemberBean> memberList  = gson.fromJson(data, new TypeToken<   ArrayList<MemberBean>    >(){}.getType());

                // 循环输出
                for(MemberBean member: memberList) {
                    Log.i("tag1", member.getUsername());
                }
            }
        });


    }
}